package com.ljy.springcloud.controller;

import com.ljy.springcloud.entities.CommonResult;
import com.ljy.springcloud.entities.Payment;
import com.ljy.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
public class PaymentController {
    @Autowired
    PaymentService paymentService;
    @Autowired
    DiscoveryClient discoveryClient;

    @Value("${server.port}")
    Integer port;

    @PostMapping("/payment/insert")
    public CommonResult insert(@RequestBody Payment payment) {
        int insert = paymentService.insert(payment);
        log.info("===插入结果：{}", insert);
        if (insert > 0) {
            return new CommonResult(200, "插入成功");
        }
        return new CommonResult(444, "插入失败");
    }

    @GetMapping("/payment/find/{id}")
    public CommonResult<Payment> find(@PathVariable(name = "id") int id) {
        log.info("===id:{}", id);
        Payment payment = paymentService.find(id);
        if (payment != null) {
            return new CommonResult<>(200, "查询成功", payment);
        }
        return new CommonResult<>(444, "未查到", null);
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("===service:{}", service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance : instances) {
            log.info("id:{}  host:{}  port:{}  uri:{}", instance.getInstanceId(), instance.getHost(), instance.getPort(), instance.getUri());
        }
        return instances;
    }

    @GetMapping("/payment/serverport")
    public String serverport() {
        return "port" + port;
    }

    @GetMapping("/payment/zipkin")
    public String paymentZipkin() {
        return "hi ,i'am paymentzipkin server fall back，welcome to here, O(∩_∩)O哈哈~";
    }

}
